package br.edu.sistemaacademico.observer;

import java.util.Vector;
import javax.swing.text.Document;

public class Observavel{

    private boolean changed = false;
    private Vector obs;
    private Document doc = null;

    public Observavel() {
        obs = new Vector();
    }
    public void setDocument(Document doc){
        this.doc = doc;
    }

    public Document getDocument(){
        return this.doc;
    }

    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o))
	    obs.addElement(o);
    }

     public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

       public void notifyObservers() {
	notifyObservers(null);
    }

     public void notifyObservers(Object arg) {
        Object[] arrLocal;

	synchronized (this) {
	    if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            //System.out.println( arrLocal[i].toString()+" "+this.toString());
            ((Observer)arrLocal[i]).update(this, arg);
    }

    public synchronized void deleteObservers() {
	obs.removeAllElements();
    }


    public synchronized void setChanged() {
	changed = true;
    }

    protected synchronized void clearChanged() {
	changed = false;
    }


    public synchronized boolean hasChanged() {
	return changed;
    }

    
    public synchronized int countObservers() {
	return obs.size();
    }

}
